﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TVShows.Data.ITVShowAdapters.Interfaces;
using TVShows.DataModels;

namespace TVShows.Data.ITVShowAdapters.Adapters
{
    public class TVShowAdapter: ITVShowAdapter
    {
        public TVShow AddTVShow(TVShow show)
        {
            using (ApplicationDbContext db = new ApplicationDbContext()) {
                show = db.TVShows.Add(show);
                db.SaveChanges();
            }
            return show;
        }

        public List<TVShow> GetAllTVShows()
        {
            List<TVShow> shows;
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                shows = db.TVShows.OrderBy(x => x.Name).ToList();
            }
            return shows;
        }

        public TVShow GetTVShow(int id)
        {
            TVShow show;
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                show = db.TVShows.Include("Characters").Where(x => x.Id == id).FirstOrDefault();
            }
            return show;
        }

        public TVShow UpdateTVShow(TVShow show)
        {
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                TVShow old = db.TVShows.Find(show.Id);
                old.Name = show.Name;
                old.Image = show.Image;
                db.SaveChanges();
            }
            return show;
        }

        public void DeleteTVShow(int id)
        {
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                TVShow show = db.TVShows.Find(id);
                db.TVShows.Remove(show);
                db.SaveChanges();
            }
        }
    }
}
